using System;
using System.Collections;

namespace Deepcode.Flux.Core.Collections
{
	/// <summary>
	/// BaseDictionary - implements a base key/value pair lookup
	/// dictionary for inheritance into your own dictionary classes.
	/// This is reused for example in the SetupDictionary and the
	/// FluxConfig classes to store and hold key/value information.
	/// </summary>
	public class BaseDictionary
	{
		/// <summary>
		/// Used by BaseDictionary derived classes, the DictionaryItem
		/// class holds one key/value pair.
		/// </summary>
		public class DictionaryItem
		{
			private string key = "";
			private string val = "";

			public string Key{ get{ return key; } set{ key=value; }}
			public string Val{ get{ return val; } set{ val=value; }}
		}
		/// <summary>
		/// The DictionaryArray array list object holds all of the
		/// key/value pairs in this particular Dictionary.
		/// </summary>
		protected Hashtable DictionaryArray = new Hashtable();
		/// <summary>
		/// Get/Set a key value in the dictionary based on the
		/// key name passed in. For set - if the key doesn't exist
		/// in the dictionary, it is created and set to the specified
		/// value. For get - if the key doesn't exist, the property
		/// returns String.Empty
		/// </summary>
		public virtual string this[string Key]
		{
			get
			{
				DictionaryItem item = (DictionaryItem) DictionaryArray[Key];
				if( item == null ) return String.Empty;
				return item.Val;
			}
			set
			{
				DictionaryItem item = (DictionaryItem) DictionaryArray[Key];
				if( item != null )
				{
					item.Val = value;
					return;
				}

				DictionaryItem newItem = new DictionaryItem();
				newItem.Key = Key;
				newItem.Val = value;
				DictionaryArray[ Key ] = newItem;
			}
		}
		/// <summary>
		/// Returns the entire dictionary as an array of DictionaryItem objects.
		/// </summary>
		/// <returns></returns>
		public DictionaryItem [] ToArray()
		{
			DictionaryItem [] items = new DictionaryItem[ DictionaryArray.Keys.Count ];
			int i = 0;
			foreach( DictionaryEntry e in this.DictionaryArray )
				items[i++] = (DictionaryItem) e.Value;

			return items;
		}
	}
}
